package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.common.CateException;
import com.itheima.common.R;
import com.itheima.service.CategoryService;
import com.itheima.mapper.CategoryMapper;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author 海关监管和对方
* @description 针对表【category(鑿滃搧鍙婂?椁愬垎绫)】的数据库操作Service实现
* @createDate 2024-05-06 10:13:07
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public R<Page> pageR(Page<Category> categoryPage, LambdaQueryWrapper<Category> wrapper) {
        categoryMapper.selectPage(categoryPage,wrapper);
        return R.success(categoryPage);
    }

    @Override
    public void deleteById(long id) {
        //判断“分类”是否与菜品或套餐关联
        //1.是：抛出异常
        //2.否：正常删除

        //查看有多少与category连接的菜品
        LambdaQueryWrapper<Dish> dishWra = new LambdaQueryWrapper<>();
        dishWra.eq(Dish::getCategoryId,id);
        long DishCount = dishService.count(dishWra);
        if(DishCount>0){
            //抛出自定义异常，并会在全局异常处理器中处理
            throw new CateException("该分类与菜品关联，无法删除");
        }

        LambdaQueryWrapper<Setmeal> SetmealWra = new LambdaQueryWrapper<>();
        SetmealWra.eq(Setmeal::getCategoryId,id);
        long SetCount = setmealService.count(SetmealWra);
        if(SetCount>0){
            throw new CateException("该分类与套餐关联，无法删除");
        }

        super.removeById(id);
    }
}




